package xyz.lwm.lazycat.web;

import com.alibaba.fastjson2.JSON;
import org.jetbrains.annotations.NotNull;
import xyz.lwm.lazycat.annotation.Bean;
import xyz.lwm.lazycat.annotation.ConditionalOnMissingBean;
import xyz.lwm.lazycat.annotation.Configuration;
import xyz.lwm.lazycat.utility.CollectionUtil;
import xyz.lwm.lazycat.utility.It;
import xyz.lwm.lazycat.web.handle.JsonMapper;
import xyz.lwm.lazycat.web.route.Route;
import xyz.lwm.lazycat.web.route.Router;

import java.util.List;


/**
 * web 配置
 *
 * @author lwm
 */
@Configuration
public class WebConfiguration {

    /**
     * 默认使用 fast2Json 实现
     */
    @Bean
    @ConditionalOnMissingBean
    public JsonMapper fast2JsonMapper() {
        return new JsonMapper() {
            @NotNull
            @Override
            public byte[] toJsonBytes(@NotNull Object obj) {
                return JSON.toJSONBytes(obj);
            }

            @NotNull
            @Override
            public <T> T fromJsonBytes(@NotNull byte[] json, @NotNull Class<T> clazz) {
                return JSON.parseObject(json, clazz);
            }
        };
    }

    /**
     * 从容器中收集通用路由, 并注册到路由表中 <br>
     * <pre>
     * 通用路由有两种方式整合:
     * 1. 实现 {@link Route} 接口, 并在容器中注册, 由当前方法统一添加路由;
     * 2. 实现 {@link Controllable} 接口, 在 {@link Controllable#control(Router)} 中手动添加 route 对象 , 并在容器中注册;
     * </pre>
     *
     * @param routes 通用路由
     * @return 路由控制器
     */
    @Bean
    public Controllable generalRoutesControllable(List<Route> routes) {
        return router -> It.of(routes).filter(CollectionUtil::isNotEmpty)
                .also(list -> list.forEach(router::add));
    }

}
